<?php

namespace app\index\controller;

use app\common\model\Article as ArticleModel;
use app\common\model\Category;
use app\common\model\TagArt as TagArtModel;
use app\common\model\Tags;
use think\Cache;

class Index extends common
{

    /*前台首页*/
    public function index()
    {
        //文章列表
        //设置文章缓存
        //根据page不同 来定义缓存的key
        $page = input('page', '1');
        $articles = unserialize(Cache::remember('indexArt_' . $page, function () {
            return serialize(ArticleModel::where('softdelete', 0)->order('aid', 'desc')->paginate(2));
        }));
        return view('', compact('articles'));
    }

    /*文章分类列表*/
    public function catelist()
    {
        $cid = input('cid');
        $catemap['softdelete'] = 0;
        $catemap['cateid'] = $cid;
        $articles = ArticleModel::where($catemap)->order('aid', 'desc')->paginate(2);
        //计算总数
        $articleCount = ArticleModel::where($catemap)->count();
        //分类名称
        $cateName = Category::find($cid);
        return view('', compact('articles', 'articleCount', 'cateName'));
    }

    /*文章标签列表*/
    public function taglist()
    {
        $tid = input('tid');
        //查询标签对应的文章表的所有aid
        $aids = TagArtModel::where('tid', $tid)->column('aid');
        $catemap['softdelete'] = 0;
        $catemap['aid'] = ['in', implode(',', $aids)];
        $articles = ArticleModel::where($catemap)->order('aid', 'desc')->paginate(2);
        //计算总数
        $articleCount = ArticleModel::where($catemap)->count();
        //标签名称
        $tagName = Tags::find($tid);
        return view('', compact('articles', 'articleCount', 'tagName'));
    }

    /*内容页*/
    public function content()
    {
        $id = input('id');
        //文章数据
        $data = ArticleModel::find($id);
        if (!$data) {
            $this->error('没有这篇文章');
        }

        //上一篇
        $prevmap['softdelete'] = 0;
        $prevmap['aid'] = ['lt', $id];
        $moreData['prev'] = ArticleModel::where($prevmap)->order('aid', 'desc')->find();

        //下一篇
        $nextmap['softdelete'] = 0;
        $nextmap['aid'] = ['gt', $id];
        $moreData['next'] = ArticleModel::where($nextmap)->order('aid', 'asc')->find();
        return view('', compact('data', 'moreData'));
    }

}
